const app = getApp();
import moment from 'moment';
import services from '../../services/clockin';
import timeHelper from '../../utils/timeHelper';
import common from '../../utils/common';

Page({
  data: {
    toadyTime: 0, // 今天
    currentTime: 0, // 当前时间
    currentMode: 'month', // 当前选择模式 month月 week周
    weekList: [{
        name: '一'
      },
      {
        name: '二'
      },
      {
        name: '三'
      },
      {
        name: '四'
      },
      {
        name: '五'
      },
      {
        name: '六'
      },
      {
        name: '日'
      }
    ], // 周列表
    slidePages: [], // 月信息
    activeDate: 0, // 选中日期
    activeDateDesc: '', // 选中日期展示
    monthAttendanceDate: [], // 月打卡记录
    constructionSiteList: [], // 日打卡记录
    isLoading: false,
    isReady: false
  },
  async onLoad() {
    // 页面显示
    console.log('onShow');
    let ct = new Date(app.globalData.serverTime);
    ct = +new Date(ct.getFullYear(), ct.getMonth(), ct.getDate());
    this.setData({
      currentTime: ct,
      toadyTime: ct
    });
    await this.initData();
    this.setData({
      isReady: true
    });
  },
  async onShow() {
    if (this.data.isReady) {
      await this.queryAttendanceRecords();
    }
  },
  async initData() {
    this.handleSlidePages();
    await this.setActiveDateInfo(this.data.currentTime);
    this.handleSlidePages();
  },
  handleSlidePages() {
    const {
      currentTime,
      currentMode
    } = this.data;
    if (currentMode === 'month') {
      const monthList = [currentTime];
      this.handleGetSlidePages(monthList);
      // new Date(year, month - 1, 1), new Date(year, month + 1, 1)
      return;
    }
  },
  handleGetSlidePages(monthList) {
    const slidePages = monthList.map((item) => {
      return {
        ...item,
        monthDate: this.getDates(item)
      };
    });
    this.setData({
      slidePages
    });
    console.log('slidePages', this.data.slidePages);
  },
  async handleActiveDate(e) {
    const {
      daytime
    } = e.currentTarget.dataset || {};
    await this.setActiveDateInfo(daytime);
  },
  async setActiveDateInfo(t) {
    if (t === this.data.activeDate) {
      return;
    }
    const ot = new Date(t);
    const year = ot.getFullYear();
    const month = ot.getMonth();
    this.setData({
      activeDate: t,
      activeDateDesc: `${year}年${month + 1}月`
    });
    await this.queryAttendanceRecords();
  },
  async queryAttendanceRecords() {
    try {
      this.setData({
        constructionSiteList: [],
        isLoading: true
      });
      const {
        unionid
      } = app.globalData.userInfo || {};
      const {
        activeDate
      } = this.data;
      await this.queryMonthRecord();
      const params = {
        day: moment(activeDate).format('YYYYMMDD')
      };
      const res = await services.getClockCalenderRecords(params, unionid);
      if (res && res.data) {
        let constructionSiteList = res.data.filter(
          (item) => !!item.start_work_time || !!item.end_work_time
        );
        constructionSiteList = constructionSiteList.map((item) => {
          const {
            station,
            start_work_time,
            end_work_time,
            shift_type
          } = item;
          const startWorkTimeStamp = start_work_time ?
            +new Date(start_work_time.replace(/\-/g, '/')) :
            '';
          const endWorkTimeStamp = end_work_time ?
            +new Date(end_work_time.replace(/\-/g, '/')) :
            '';
          let totalTime = '';
          if (startWorkTimeStamp && endWorkTimeStamp) {
            totalTime = timeHelper.getTotalTime((endWorkTimeStamp - startWorkTimeStamp) / 1000);
          }
          let startWorkTime = '';
          let endWorkTime = '';
          console.log('queryAttendanceRecords======', startWorkTimeStamp, endWorkTimeStamp);
          if (startWorkTimeStamp) {
            const sat = timeHelper.getSeconds(startWorkTimeStamp);
            startWorkTime = timeHelper.formatTime(sat, false);
          }
          if (endWorkTimeStamp) {
            const eat = timeHelper.getSeconds(endWorkTimeStamp);
            endWorkTime = timeHelper.formatTime(eat, false);
          }
          const shiftTypeMap = {
            0: '白班',
            1: '夜班'
          };
          return {
            stationName: station && station.name ? station.name : '',
            stationId: station && station.id ? station.id : '',
            startWorkTime,
            endWorkTime,
            totalTime,
            shiftType: shift_type,
            shiftTypeDesc: shiftTypeMap[shift_type] || ''
          };
        });
        this.setData({
          constructionSiteList,
          isLoading: false
        });
        console.log('queryAttendanceRecords', res, constructionSiteList);
      } else {
        common.showErrorToast(res);
      }
    } catch (error) {
      console.log('获取打卡状态失败', error);
      common.showErrorToast(error);
    }
  },
  async queryMonthRecord() {
    try {
      const {
        unionid
      } = app.globalData.userInfo || {};
      const {
        activeDate
      } = this.data;
      const year = moment(activeDate).format('YYYY');
      const month = moment(activeDate).format('MM');
      const params = {
        year,
        month
      };
      const res = await services.getClockCalenderMonth(params, unionid);
      if (res && res.data) {
        const monthList = res.data.map((item) => {
          return +new Date(item.replace(/\-/g, '/'));
        });
        console.log('queryMonthRecord--success', monthList);
        this.setData({
          monthAttendanceDate: monthList
        });
      }
      console.log('queryMonthRecord', res);
    } catch (error) {
      console.log('queryMonthRecord error', error);
    }
  },

  onPrev() {
    const {
      currentTime
    } = this.data;
    const newCT = moment(currentTime).subtract(1, 'months').startOf('month').valueOf();
    this.setData({
      currentTime: newCT,
      monthAttendanceDate: []
    });
    this.initData();
  },
  onNext() {
    const {
      currentTime
    } = this.data;
    const newCT = moment(currentTime).subtract(-1, 'months').startOf('month').valueOf();
    this.setData({
      currentTime: newCT,
      monthAttendanceDate: []
    });
    this.initData();
  },
  onChangeMode() {},
  getDates(t) {
    const ot = new Date(t);
    return this.getMonthDates(ot);
    // return this.currentMode === 'month' ? this.getMonthDates(date) : this.getWeekDates(date)
  },
  getMonthDates(date) {
    // 当前月第一天
    const monthFirstDay = new Date(date.getFullYear(), date.getMonth(), 1);

    // 当前月是周几
    const monthFirstDayWeek = monthFirstDay.getDay() || 7;

    // 当前月最后一天
    const monthLashDay = new Date(date.getFullYear(), date.getMonth() + 1, 0);

    // 当前月最后一天是周几
    const monthLashDayWeek = monthLashDay.getDay() || 7;

    // 获取上个月最后一天,因为日历的周一可能不是本月
    const prevMonthLastDate = new Date(date.getFullYear(), date.getMonth(), 0);

    // 时间数组
    const prevDates = [];
    const currentDates = [];
    const nextDates = [];

    for (var i = 0; i < monthFirstDayWeek + monthLashDay.getDate() + (7 - monthLashDayWeek); i++) {
      // 计算日历上个月天数
      if (i < monthFirstDayWeek - 1) {
        prevDates.unshift(
          new Date(date.getFullYear(), date.getMonth() - 1, prevMonthLastDate.getDate() - i)
        );
        continue;
      }

      // 计算日历下个月天数
      if (i > prevMonthLastDate.getDate() + monthFirstDayWeek) {
        nextDates.push(
          new Date(
            date.getFullYear(),
            date.getMonth() + 1,
            i - (monthFirstDayWeek + monthLashDay.getDate()) + 1
          )
        );
        continue;
      }

      // 计算日历这个月天数
      if (i > monthFirstDayWeek - 1) {
        currentDates.push(new Date(date.getFullYear(), date.getMonth(), i - monthFirstDayWeek + 1));
        continue;
      }
    }

    let days = [...prevDates, ...currentDates, ...nextDates];
    days = days.map((d) => {
      return {
        dayTime: +d,
        dayNum: d.getDate(),
        dayClass: this.handleGetDayClass(+d)
      };
    });
    // 将时间按每 7 天分割返回
    const weekDays = [];
    const loopNum = days.length % 7 === 0 ? days.length / 7 : parseInt(days.length / 7) + 1;
    for (let i = 0; i < loopNum; i++) {
      weekDays.push(days.splice(0, 7));
    }
    console.log('weekDays', days, weekDays);
    return weekDays;
  },
  handleGetDayClass(d) {
    let res = '';
    if (this.isToday(d)) {
      res = `${res} is-today`;
    }
    if (this.isWorkDay(d)) {
      res = `${res} is-work-day`;
    }
    if (this.isOtherMonth(d) && this.data.currentMode === 'month') {
      res = `${res} is-other-month`;
    }
    return res;
  },
  // 是否是今天
  isToday(date) {
    const today = this.data.toadyTime;
    const tt = new Date(today);
    const dt = new Date(date);
    return (
      tt.getFullYear() === dt.getFullYear() &&
      tt.getMonth() === dt.getMonth() &&
      tt.getDate() === dt.getDate()
    );
  },
  // 是工作日
  isWorkDay(date) {
    return this.data.monthAttendanceDate.includes(date);
  },
  // 是否为非当前月
  isOtherMonth(date) {
    const today = this.data.currentTime;
    const tt = new Date(today);
    const dt = new Date(date);
    return dt.getMonth() !== tt.getMonth();
  },
  // 被选中的那一天
  isActiveDay(date) {
    const at = new Date(this.data.activeDate);
    const dt = new Date(date);
    return (
      at.getFullYear() === dt.getFullYear() &&
      at.getMonth() === dt.getMonth() &&
      at.getDate() === dt.getDate()
    );
  },
  onChangeMode() {
    this.setData({
      currentMode: this.data.currentMode === 'month' ? 'week' : 'month'
    });
  },
  handleReissue(e) {
    const {
      info,
      clockType,
    } = e.currentTarget.dataset || {};
    const {
      stationId,
      shiftType,
    } = info || {}
    let url = '/page/reissue/reissue';
    url = url + `?stationId=${stationId||''}&mode=${stationId||!info?0:1}&clockType=${clockType||0}&shiftType=${shiftType||0}`;
    dd.navigateTo({
      url
    });
  },
  handleGoReissueRecord() {
    dd.navigateTo({
      url: '/page/reissueRecords/reissueRecords'
    });
  }
});